<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Core_Controllers_Plugins_Permalink extends Gio_Core_Plugin
{
	private $_inArray = array(
		'news_article_category', 'news_article_details',
	);
	
	public function run()
	{
		$request = Gio_Core_Request::getInstance();
		$configs = Gio_Core_Config_Xml::getConfig('web');
		/**
		 * Do nothing if we are in page of managing permalink
		 */
		$uri = $request->getRequestUri();
		$uri = strtolower($uri);
		$uri = rtrim($uri, '/') . '/';
		$adminPrefix = $configs->admin->url_prefix;
		$adminPrefix = rtrim(ltrim($adminPrefix, '/'), '/');
		if (is_int(strpos($uri, '/' . $adminPrefix . '/core/permalink'))) {
			return;
		}
		
		$defaultFile = ROOT_DIR . DS . 'configs' . DS . 'permalink.xml';
		
		$host = $request->getServerName();
		$host = (substr($host, 0, 3) == 'www') ? substr($host, 4) : $host;
		$file = ROOT_DIR . DS . 'configs' . DS . $host . '.' . 'permalink.xml';
		
		$file = file_exists($file) ? $file : $defaultFile;
		if (!file_exists($file)) {
			return;
		}
		
		$route = Gio_Core_Route::getInstance();
		$config = @simplexml_load_file($file);
		if (!isset($config->item) || empty($config->item)) {
			return;
		}
		
		$categoryConfig = Gio_Core_Module::getConfig('category');
		$param = isset($categoryConfig['url']['param']) 
							? $categoryConfig['url']['param'] : 'category_id';
		
		foreach ($config->item as $index => $item) {
			$item = (array)$item;
			if (!in_array($item['name'], $this->_inArray)) {
				$route->setRoute($item['name'], $item);
			} elseif ($param == 'category_path' && in_array($item['name'], $this->_inArray)) {
				$route->setRoute($item['name'], $item);
			}
		}
	}
}
